/**
 * Created by wtfssd on 2017/9/15.
 */

import React, {PropTypes, Component} from 'react'
import {StyleSheet, Text, View, WebView, TouchableOpacity} from 'react-native'
import {connect} from 'react-redux'
import {} from 'antd-mobile'
import NavigationBar from 'react-native-navbar'
import {Actions, ActionConst} from 'react-native-router-flux'
import CommonStyle, {Color, size} from '../../../assets/styles/index'
import {BackButton, Line, Star} from '../../common/index'
const patchPostMessageFunction = function() {
    const originalPostMessage = window.postMessage;

    const patchedPostMessage = function(message, targetOrigin, transfer) {
        originalPostMessage(message, targetOrigin, transfer);
    };

    patchedPostMessage.toString = function() {
        return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
    };

    window.postMessage = patchedPostMessage;
};

const patchPostMessageJsCode = '(' + String(patchPostMessageFunction) + ')();';
class Page extends Component {
    webview = null;
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    /*组件将要加载*/
    componentWillMount() {

    }

    /*组件已经加载*/
    componentDidMount() {

    }

    /*组件将要卸载*/
    componentWillUnmount() {

    }


    onMessage(e){
        console.log('onMessage',e.data);
        // alert(`message from ${e.data}`);
    }
    render() {
        return (
            <View style={Styles.container}>
                <NavigationBar tintColor={Color.primary}
                               statusBar={{style: 'light-content'}}
                               title={{title: this.props.title, tintColor: 'white'}}
                               leftButton={<BackButton/>}
                />
                <WebView style={{flex: 1}}
                         ref={webview => { this.webview = webview; }}
                         injectedJavaScript={patchPostMessageJsCode}
                         javaScriptEnabled
                         domStorageEnabled
                         source={require('../../../thirdParty/web/map.html')}
                         onNavigationStateChange={(e)=>{
                             console.log('onNavigationStateChange',e);
                         }}
                         onMessage = {(e)=>{
                             if (typeof e === 'object'){
                                 console.log('onMessage',e.nativeEvent);
                                 this.onMessage(e.nativeEvent);
                             }
                         }}
                         onLoadEnd = {(e)=>{
                             this.webview.postMessage(JSON.stringify({user:'233',data:'adasda'}));
                         }}

                />
            </View>
        )
    }
}

const Styles = StyleSheet.create({
    container: {
        display: 'flex',
        flex: 1,
    }
});

export default connect(
    ({home}) => ({home})
)(Page)



